const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')
const onerror = require('koa-onerror')
const logger = require('koa-logger')
const fs = require("fs");
const path = require("path");
const proxy = require('koa2-proxy-middleware');
// error handler
onerror(app)

// middlewares
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

const options = {
  targets: {
    '/api/(.*)': {
      target: 'http://175.24.203.134:8090',
      ws: true,
      changeOrigin: true,
      pathRewrite: {
        '^/api/': '' //和前端代理一样,选择api替换为什么
      }
    },
    '/prod-api/(.*)': {
      target: 'http://applet-admin-test.blmdz.cn/prod-api/',
      ws: true,
      changeOrigin: true,
      pathRewrite: {
        '^/prod-api/': '' //和前端代理一样,选择api替换为什么
      }
    },
  }
}

app.use(proxy(options));

// logger
app.use(async (ctx, next) => {
  if (ctx.url == "/") {
    await next();
  } else {
    const html = await fs.readFileSync(path.resolve(__dirname + "/public/index.html"));
    ctx.body = html.toString();
  }
})

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
